package Thread.letter;

import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class Test4 {
    @Test
    void test() {
        List<String> list = new ArrayList<>();
        Object lock = new Object();
        new Thread(new Test3Thread1(list, lock)).start();
        new Thread(new Test3Thread2(list, lock)).start();
    }
}

class Test3Thread3 implements Runnable {
    private List<String> list;
    private Object lock;

    public Test3Thread3(List<String> list, Object lock) {
        this.list = list;
        this.lock = lock;
    }

    @Override
    public void run() {
        synchronized (lock) {
            if (list.size() != 5) {
                System.out.println("开始等待，此时list的长度为：" + list.size());
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("等待结束，此时list的长度为： " + list.size());
                lock.notify();
            }
        }
    }
}

class Test3Thread4 implements Runnable {
    private List<String> list;
    private Object lock;

    public Test3Thread4(List<String> list, Object lock) {
        this.list = list;
        this.lock = lock;
    }

    @Override
    public void run() {
        synchronized (lock) {
            for (int i = 0; i < 10; i++) {
                list.add("aaa");
                System.out.println("添加了" + list.size() + "个元素");
                if (list.size() == 5) {
                    lock.notify();
                    System.out.println("满足需求，通知已发出");
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}